package com.ti.shangou.util.Permission;

import com.ti.shangou.pojo.vo.PermissionVO;
import com.ti.shangou.pojo.vo.RoleVO;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 作者：田宝山
 * 日期：2020/6/1
 */
public class SetPermission {
    public static List<RoleVO> setPermissionsOfRoles(List<RoleVO> roleVOS, List<PermissionVO> permissionVOS){
        if (roleVOS!=null&&roleVOS.size()>0&&permissionVOS!=null&&permissionVOS.size()>0){
            Map<Integer, List<PermissionVO>> perCollect = permissionVOS.stream().collect(Collectors.groupingBy(PermissionVO::getPermissionId));
            for (RoleVO roleVO:roleVOS) {
                String permissions = roleVO.getPermissions();
                String[] split = {};
                if (permissions!=null&&permissions.length()>0){
                    split = permissions.split(",");
                }
                List list = new ArrayList<>();
                if (split.length>0){
                    for (String p:split) {
                        if (StringUtils.isEmpty(p))
                            continue;
                        List<PermissionVO> permissionVOList = perCollect.get(Integer.parseInt(p));
                        // 拆箱
                        if (!StringUtils.isEmpty(permissionVOList)){
                            PermissionVO permissionVO = permissionVOList.get(0);
                            list.add(permissionVO);
                        }
                    }
                }
                roleVO.setPermissionVOS(list);
            }
        }
        return roleVOS;
    }
}
